﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.Process
{
    public partial class ProcessDataForm : 
   
     DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _processApiBaseUrl = "https://localhost:7222";
        public ProcessDataForm()
        {          
            InitializeComponent(); 
             // 1. 创建CheckEdit编辑器
            var repositoryItemCheckEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
            gridControl1.RepositoryItems.Add(repositoryItemCheckEdit);

            // 2. 创建Unbound列
            var gridColumnCheck = new DevExpress.XtraGrid.Columns.GridColumn();
            gridColumnCheck.Caption = "选择";
            gridColumnCheck.Name = "gridColumnCheck";
            gridColumnCheck.UnboundType = DevExpress.Data.UnboundColumnType.Boolean; // 不绑定数据源
            gridColumnCheck.Visible = true;
            gridColumnCheck.VisibleIndex = 0; // 放在第一列
            gridColumnCheck.ColumnEdit = repositoryItemCheckEdit;

            // 3. 添加到GridView
            gridView1.Columns.Insert(0, gridColumnCheck);
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            this.Load += ProcessDataForm_Load;
           
        }
        public class ProcessModel
        {
            public bool IsSelected { get; set; }///是否选中
            public long Id { get; set; }///主键
            public string ProcessCode { get; set; } // 工序编码         
            public string ProcessName { get; set; } // 工序名称           
            public string ProcessExplain { get; set; } // 工序说明            
            public string ProcessDesc { get; set; } // 工序备注           
            public string ProcessHead { get; set; } // 工序负责人
           public  string ProcessMaterials { get; set;}///工业物料
            public string ProcessDepartment { get; set; } // 工序部门          
            public string Processworkshop { get; set; } // 工序车间                    
            public bool ProcessadEnable { get; set; }  /// 工序是否启用
        }
        private async void ProcessDataForm_Load(object sender, EventArgs e)
        {
            await  LoasProcessData();
        }

        private async Task LoasProcessData()
        {
            var process = await GetProcessAsync<List<ProcessModel>>("api/ProcessModel/ShowProcess");

            gridControl1.DataSource = null;
            gridControl1.DataSource = process;

            gridView1.PopulateColumns();
            gridView1.BestFitColumns();
            gridView1.RefreshData();
        }
       private async Task<T> GetProcessAsync<T>(string endpoint)
       {
            HttpResponseMessage repoonse=await _httpClient.GetAsync($"{_processApiBaseUrl}/{endpoint}");
            repoonse.EnsureSuccessStatusCode();
            string responseBody = await repoonse.Content.ReadAsStringAsync();

            Console.WriteLine($"API响应:{responseBody}");
            var josnobject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            

            if (josnobject["pagingData"] != null)
            { 
                string dataJson = josnobject["pagingData"].ToString();
                Console.WriteLine($"提取的pageDatas字段:{dataJson}");

                return JsonConvert.DeserializeObject<T>(dataJson);
            }
            return JsonConvert.DeserializeObject<T>(responseBody);
       }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            var addForm = new AddProcessForm();
            addForm.ShowDialog(); // 这是弹出，不是跳转
        }

        private async void simpleButton3_Click(object sender, EventArgs e)
        {
            await LoasProcessData();
        }

        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            int rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0)
            {
                XtraMessageBox.Show("请先选择要修改的行！");
                return;
            }

            var model = new ProcessModel
            {
                Id = Convert.ToInt64(gridView1.GetRowCellValue(rowHandle, "Id")),
                ProcessName = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessName")),
                ProcessExplain = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessExplain")),
                ProcessDesc = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessDesc")),
                ProcessHead = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessHead")),
                ProcessDepartment = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessDepartment")),
                Processworkshop = Convert.ToString(gridView1.GetRowCellValue(rowHandle, "Processworkshop")),
                ProcessMaterials=Convert.ToString(gridView1.GetRowCellValue(rowHandle, "ProcessMaterials")),
                ProcessadEnable=Convert.ToBoolean(gridView1.GetRowCellValue(rowHandle, "ProcessadEnable")),
                // 其他字段根据需要补充
            };

            var editForm = new ProcessUpdateForm(model);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                // 编辑成功后刷新
                LoasProcessData();
            }

        }
        /// <summary>
        /// 批量删除方法
        /// </summary>
        private async void simpleButton4_Click (object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelected");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            using (var client = new HttpClient { BaseAddress = new Uri(_processApiBaseUrl) })
            {
                foreach (var id in checkedIds)
                {
                    var resp = await client.DeleteAsync($"/api/ProcessModel/DeleteProcessModel?Id={id}");
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }
            await LoasProcessData();
            XtraMessageBox.Show("删除完成！");
        }
    }
}